<?php

namespace App\Admin\Controllers\App;

use App\Admin\Actions\App\SetupApplicationOss;
use App\Admin\Actions\Batches\BatchDisable;
use App\Admin\Actions\Batches\BatchEnable;
use App\Admin\Traits\WithUploads;
use App\Models\Application;
use Dcat\Admin\Exception\InvalidArgumentException;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Models\Administrator;
use Illuminate\Support\Carbon;

class ApplicationController extends AdminController
{
    use WithUploads;

    protected string $title = '应用管理';

    protected array $description = [
        'index' => '应用由系统管理员设置，权限不会给普通用户',
    ];

    /**
     * @throws InvalidArgumentException
     */
    public function grid(): Grid
    {
        return Grid::make(Application::with('admin')->latest(), function (Grid $grid) {
            $grid->batchActions([
                new BatchEnable(Application::class),
                new BatchDisable(Application::class),
            ]);
            $grid->enableDialogCreate();
            $grid->showQuickEditButton();
            $grid->disableEditButton();

            $grid->actions([
                new SetupApplicationOss,
            ]);

            $grid->quickSearch(['name', 'app_key'])
                ->placeholder('应用名称/App Key');

            $grid->column('id');
            $grid->column('name');
            $grid->column('app_key', 'App Key');
            $grid->column('admin.name', '所属用户');
            $grid->column('expired_at')
                ->sortable();
            $grid->column('status')
                ->bool();
            $grid->column('created_at');
        });
    }

    /**
     * @throws InvalidArgumentException
     */
    public function form(): Form
    {
        return Form::make(Application::class, function (Form $form) {
            $form->text('name', '应用名称')
                ->required();
            $form->select('admin_id', '所属用户')
                ->rules('required|unique:App\Models\Application,admin_id,'.$form->model()->id, [
                    'unique' => '每个用户只允许有一个应用',
                ])
                ->required()
                ->options(Administrator::pluck('name', 'id'));
            $form->datetime('expired_at')
                ->default(Carbon::today()->addYear());
            $form->switch('status', '状态')
                ->default(true);
        });
    }
}
